const Video = require("../models/Video");
const Course = require("../models/Course");

class VideoService {
  // 获取课程下的所有视频
  async getVideosByCourseId(courseId) {
    try {
      const course = await Course.findByPk(courseId);
      if (!course) {
        return false;
      }
      return await Video.findAll({
        where: { courseId },
      });
    } catch (error) {
      console.error("获取课程下的所有视频时出错：", error);
      throw error;
    }
  }

  // 创建视频
  async createVideo({ courseId, title, description, url }) {
    try {
      const course = await Course.findByPk(courseId);
      if (!course) {
        return false;
      }
      return await Video.create({
        title,
        description,
        url,
        courseId,
      });
    } catch (error) {
      console.error("创建视频时出错：", error);
      throw error;
    }
  }
  // 获取单个视频
  async getVideoById({ courseId, videoId }) {
    try {
      const course = await Course.findByPk(courseId);
      if (!course) {
        return false;
      }

      return await Video.findOne({
        where: { id: videoId, courseId },
      });
    } catch (error) {
      console.error("获取单个视频时出错：", error);
      throw error;
    }
  }

  // 更新视频
  async updateVideo({ courseId, videoId, title, description, url }) {
    try {
      const course = await Course.findByPk(courseId);
      if (!course) {
        return false;
      }

      const video = await Video.findOne({
        where: { id: videoId, courseId },
      });

      if (!video) {
        return false;
      }

      video.title = title;
      video.description = description;
      video.url = url;

      return await video.save();
    } catch (error) {
      console.error("更新视频时出错：", error);
      throw error;
    }
  }

  // 删除视频
  async deleteVideo({ courseId, videoId }) {
    try {
      const course = await Course.findByPk(courseId);
      if (!course) {
        return false;
      }

      const video = await Video.findOne({
        where: { id: videoId, courseId },
      });

      if (!video) {
        return false;
      }

      return await video.destroy();
    } catch (error) {
      console.error("删除视频时出错：", error);
      throw error;
    }
  }

  // 批量删除视频
  async deleteVideos({ courseId, videoIds }) {
    try {
      const course = await Course.findByPk(courseId);
      if (!course) {
        return false;
      }

      const videos = await Video.findAll({
        where: { id: videoIds, courseId },
      });

      if (videos.length === 0) {
        return false;
      }

      return await Video.destroy({
        where: { id: videoIds, courseId },
      });
    } catch (error) {
      console.error("批量删除视频时出错：", error);
      throw error;
    }
  }
}

module.exports = new VideoService();
